import React, { useState, useEffect, useRef } from 'react';
import { Layout, Button, Card, Row, Col, Typography, Space, message, Spin, AutoComplete } from 'antd';
import { SearchOutlined, LineChartOutlined, DollarOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import StockInfo from './components/StockInfo';
import FinancialMetrics from './components/FinancialMetrics';
import RiskAnalysis from './components/RiskAnalysis';
import StockChart from './components/StockChart';
import InvestmentRecommendation from './components/InvestmentRecommendation';
import './App.css';

const { Header, Content } = Layout;
const { Title } = Typography;

function App() {
  const [stockSymbol, setStockSymbol] = useState('');
  const [currentStock, setCurrentStock] = useState('');
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('info');
  const [suggestions, setSuggestions] = useState([]);
  const [searching, setSearching] = useState(false);
  const searchTimeoutRef = useRef(null);

  // API基础URL
  const API_BASE_URL = process.env.NODE_ENV === 'production' ? '' : 'http://localhost:5000';

  // 搜索股票建议
  const fetchSuggestions = async (query) => {
    if (!query || query.length < 1) {
      setSuggestions([]);
      return;
    }

    setSearching(true);
    try {
      const response = await fetch(`${API_BASE_URL}/api/stock/search?q=${encodeURIComponent(query)}&limit=8`);
      if (response.ok) {
        const data = await response.json();
        const options = data.suggestions.map(stock => ({
          value: stock.symbol,
          label: (
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div>
                <strong>{stock.symbol}</strong>
                <span style={{ marginLeft: 8, color: '#666' }}>{stock.name}</span>
              </div>
              <div style={{ display: 'flex', gap: '4px' }}>
                {stock.exchange && (
                  <span style={{ fontSize: '11px', color: '#666', background: '#e8f4f8', padding: '2px 4px', borderRadius: '2px' }}>
                    {stock.exchange}
                  </span>
                )}
                <span style={{ fontSize: '12px', color: '#999', background: '#f0f0f0', padding: '2px 6px', borderRadius: '3px' }}>
                  {stock.sector}
                </span>
              </div>
            </div>
          ),
          symbol: stock.symbol,
          name: stock.name,
          sector: stock.sector,
          exchange: stock.exchange
        }));
        setSuggestions(options);
      } else {
        console.error('搜索API调用失败:', response.status);
        setSuggestions([]);
      }
    } catch (error) {
      console.error('获取建议失败:', error);
      setSuggestions([]);
    } finally {
      setSearching(false);
    }
  };

  // 防抖搜索
  const handleSearchChange = (value) => {
    setStockSymbol(value);

    // 清除之前的定时器
    if (searchTimeoutRef.current) {
      clearTimeout(searchTimeoutRef.current);
    }

    // 设置新的定时器
    searchTimeoutRef.current = setTimeout(() => {
      fetchSuggestions(value);
    }, 300);
  };

  // 处理选择建议
  const handleSelect = (_, option) => {
    setStockSymbol(option.symbol);
    // 自动触发搜索
    setTimeout(() => {
      handleSearchWithSymbol(option.symbol);
    }, 100);
  };

  const handleSearchWithSymbol = async (symbol) => {
    if (!symbol.trim()) {
      message.warning('请输入股票代码');
      return;
    }

    setLoading(true);
    try {
      const response = await fetch(`${API_BASE_URL}/api/stock/${symbol.toUpperCase()}`);
      if (!response.ok) {
        throw new Error('股票代码不存在或无法获取数据');
      }

      setCurrentStock(symbol.toUpperCase());
      setActiveTab('info');
      message.success(`成功加载 ${symbol.toUpperCase()} 的数据`);
    } catch (error) {
      message.error(`获取股票数据失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = () => {
    handleSearchWithSymbol(stockSymbol);
  };

  const handleKeyPress = (e) => {
    if (e.key === 'Enter') {
      handleSearch();
    }
  };

  // 清理定时器
  useEffect(() => {
    return () => {
      if (searchTimeoutRef.current) {
        clearTimeout(searchTimeoutRef.current);
      }
    };
  }, []);

  return (
    <Layout className="app-layout">
      <Header className="app-header">
        <Title level={3} style={{ color: 'white', margin: 0 }}>
          📊 股票投资分析工具
        </Title>
      </Header>

      <Content style={{ padding: '20px' }}>
        <Card style={{ marginBottom: '20px' }}>
          <Row gutter={[16, 16]} align="middle">
            <Col flex="auto">
              <AutoComplete
                style={{ width: '100%' }}
                size="large"
                placeholder="输入股票代码 (如: AAPL, TSLA, MSFT)"
                value={stockSymbol}
                onChange={handleSearchChange}
                onSelect={handleSelect}
                onKeyPress={handleKeyPress}
                options={suggestions}
                notFoundContent={searching ? <Spin size="small" /> : '未找到匹配的股票'}
                filterOption={false}
                defaultActiveFirstOption={false}
              />
            </Col>
            <Col>
              <Button
                type="primary"
                size="large"
                icon={<SearchOutlined />}
                onClick={handleSearch}
                loading={loading}
              >
                查询
              </Button>
            </Col>
          </Row>
        </Card>

        {loading && (
          <Card>
            <div style={{ textAlign: 'center', padding: '50px' }}>
              <Spin size="large" />
              <div style={{ marginTop: '20px' }}>正在获取数据...</div>
            </div>
          </Card>
        )}

        {currentStock && !loading && (
          <Space direction="vertical" size="large" style={{ width: '100%' }}>
            {/* 导航标签 */}
            <Card>
              <Space size="large">
                <Button
                  type={activeTab === 'info' ? 'primary' : 'default'}
                  icon={<DollarOutlined />}
                  onClick={() => setActiveTab('info')}
                >
                  基本信息
                </Button>
                <Button
                  type={activeTab === 'financial' ? 'primary' : 'default'}
                  icon={<LineChartOutlined />}
                  onClick={() => setActiveTab('financial')}
                >
                  财务指标
                </Button>
                <Button
                  type={activeTab === 'risk' ? 'primary' : 'default'}
                  icon={<ExclamationCircleOutlined />}
                  onClick={() => setActiveTab('risk')}
                >
                  风险评估
                </Button>
                <Button
                  type={activeTab === 'chart' ? 'primary' : 'default'}
                  icon={<LineChartOutlined />}
                  onClick={() => setActiveTab('chart')}
                >
                  价格走势
                </Button>
                <Button
                  type={activeTab === 'recommendation' ? 'primary' : 'default'}
                  icon={<SearchOutlined />}
                  onClick={() => setActiveTab('recommendation')}
                >
                  投资建议
                </Button>
              </Space>
            </Card>

            {/* 内容区域 */}
            {activeTab === 'info' && <StockInfo symbol={currentStock} />}
            {activeTab === 'financial' && <FinancialMetrics symbol={currentStock} />}
            {activeTab === 'risk' && <RiskAnalysis symbol={currentStock} />}
            {activeTab === 'chart' && <StockChart symbol={currentStock} />}
            {activeTab === 'recommendation' && <InvestmentRecommendation symbol={currentStock} />}
          </Space>
        )}

        {!currentStock && !loading && (
          <Card>
            <div style={{ textAlign: 'center', padding: '50px', color: '#999' }}>
              <Title level={4}>欢迎使用股票分析工具</Title>
              <p>输入股票代码开始分析，如 AAPL (苹果), TSLA (特斯拉), MSFT (微软)</p>
              <p>支持美股、港股、A股等多种市场股票查询</p>
            </div>
          </Card>
        )}
      </Content>
    </Layout>
  );
}

export default App;
